<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检查员" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入检查员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column label="路线名称" align="center" prop="routeName" />
      <el-table-column label="巡检员" align="center" prop="userName" />
      <el-table-column label="任务开始时间" align="center" prop="createTime" />
      <el-table-column label="设备上传时间" align="center" prop="beginTime" />
      <el-table-column label="设备最新时间" align="center" prop="lastTime" />
      <el-table-column label="任务结束时间" align="center" prop="endTime" />
      <el-table-column label="巡线时长" align="center">
        <template slot-scope="scope">
          <span class="ongoing-patrol">
            {{ calculatePatrolDuration(scope.row) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.roue_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-compass"
            class="trace-compare-btn"
            @click="handleUpdate(scope.row)"
          >轨迹比较</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <Guiji ref="guiji" @fetchData="getList"></Guiji>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/linepatrol/patrolRouteRecord/patrolRouteRecord";
import Guiji from "./components/PatrolRouteRecordManagementEdit";

export default {
  name: "Record",
  components: { Guiji },
  dicts: ['roue_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡线记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 定时器用于更新进行中的任务
      updateTimer: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        devid: null,
        devname: null,
        userId: null,
        userName: null,
        routeId: null,
        routeName: null,
        sign: null,
        beginTime: null,
        endTime: null,
        trail: null,
        lastTime: null,
        type: null,
        state: null,
        version: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 启动定时器，每分钟更新一次进行中的任务时长
    this.updateTimer = setInterval(() => {
      this.updateOngoingPatrols();
    }, 60000); // 每分钟更新一次
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.updateTimer) {
      clearInterval(this.updateTimer);
    }
  },
  methods: {
    /** 查询巡线记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 计算巡线时长 */
    calculatePatrolDuration(row) {
      try {
        // 验证开始时间有效性
        if (!row.createTime) {
          return '0小时0分';
        }

        const startTime = new Date(row.createTime);
        if (isNaN(startTime.getTime())) {
          return '时间格式错误';
        }

        // 确定结束时间：如果任务结束时间存在则使用结束时间，否则使用当前时间
        const endTime = row.endTime ? new Date(row.endTime) : new Date();

        if (isNaN(endTime.getTime())) {
          return '时间格式错误';
        }

        const durationMs = endTime - startTime;

        // 处理时间差为负的情况
        if (durationMs < 0) {
          return '0小时0分';
        }

        // 计算小时和分钟
        const hours = Math.floor(durationMs / (1000 * 60 * 60));
        const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));

        return `${hours}小时${minutes}分`;

      } catch (error) {
        console.error('计算巡线时长出错:', error);
        return '计算错误';
      }
    },

    /** 更新进行中的巡线任务时长 */
    updateOngoingPatrols() {
      // 查找所有进行中的任务（endTime为null）
      const ongoingRows = this.recordList.filter(row => !row.endTime);

      if (ongoingRows.length > 0) {
        // 强制更新视图，重新计算时长
        this.$forceUpdate();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        devid: null,
        devname: null,
        userId: null,
        userName: null,
        routeId: null,
        routeName: null,
        sign: null,
        beginTime: null,
        endTime: null,
        trail: null,
        lastTime: null,
        type: null,
        state: null,
        version: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡线记录";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.id) {
        this.$refs["guiji"].show(row);
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除巡线记录编号为"' + ids + '"的数据项？').then(function() {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.ongoing-patrol {
  color: #1890ff;
  font-weight: bold;
}

.trace-compare-btn {
  font-weight: 500;
  border: 1px solid #409eff;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #FFF;
  border-radius: 4px;
  transition: all 0.3s ease;
  padding: 8px 10px !important;
  font-size: 14px !important;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

.trace-compare-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

.trace-compare-btn .el-icon-compass {
  margin-right: 4px;
  font-size: 14px;
}
</style>
